# coding: utf-8
# auth: xd
# linux concurrent remote execution of commands

from io import StringIO
import paramiko
import threading

class SshClient:
    "A wrapper of paramiko.SSHClient"
    TIMEOUT = 4

    def __init__(self, host, port, username, password, command, sudo=False,key=None, passphrase=None):
     self.username = username
     self.password = password
     self.command = command
     self.sudo = sudo
     self.client = paramiko.SSHClient()
     self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
     if key is not None:
       key = paramiko.RSAKey.from_private_key(StringIO(key), password=passphrase)
     self.client.connect(host, port, username=username, password=password, pkey=key, timeout=self.TIMEOUT)
     feed_password = False
     if sudo and self.username != "root":
       command = "sudo -S -p '' %s" % command
       feed_password = self.password is not None and len(self.password) > 0
     stdin, stdout, stderr = self.client.exec_command(command,get_pty=True)
     if feed_password:
       stdin.write(self.password + "\n")
       stdin.flush()
     print (" ".join (stdout.readlines()).replace(password,''), " E ".join (stderr.readlines()), stdout.channel.recv_exit_status())
     # return {'out': stdout.readlines(),
     #   'err': stderr.readlines(),
     #   'retval': stdout.channel.recv_exit_status()}
     if self.client is not None:
       self.client.close()
       self.client = None

if __name__ == "__main__":
    # host = '10.101.0.230'
    ips = ["10.101.0.230","10.101.0.155","10.101.0.157","10.101.0.122"]
    username = 'root'
    password = 'passwd'
    port = 22
    command = 'sleep 10 && ls -l /root'
    for host in ips:
        try:
            # 是否执行sudo
            sudo=True
            # 创建多线程
            t = threading.Thread (target = SshClient, args = (host, port,username, password, command, sudo))
            # 启用多线程
            t.start ()
        except ValueError as ret:
            print(ret)

